package com.huashi.dealer.modular.business.address.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.User;
import com.huashi.dealer.commonEntity.UserAddress;
import com.huashi.dealer.core.exception.CommonException;
import com.huashi.dealer.core.util.BizAssertUtil;
import com.huashi.dealer.core.util.SaTokenUtil;
import com.huashi.dealer.modular.business.address.mapper.UserAddressMapper;
import com.huashi.dealer.modular.business.address.param.AddressInfo;
import com.huashi.dealer.modular.business.address.param.AddressListsVo;
import com.huashi.dealer.modular.business.address.param.AddressResponseParam;
import com.huashi.dealer.modular.business.address.param.AddressWithRegion;
import com.huashi.dealer.modular.business.address.service.AddressService;
import com.huashi.dealer.modular.business.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * API地址Service实现类
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
@Service("apiAddressServiceImpl")
public class AddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements AddressService {

    private final UserService userService;

    public AddressServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public AddressListsVo getAddressList() {
        AddressListsVo responseParam = new AddressListsVo();
        
        try {
            Long id = SaTokenUtil.getLoginId();
            User user = userService.getById(id);
            List<AddressInfo> list=this.baseMapper.getAddressListByUserId(id);
            responseParam.setDefaultId(user.getAddressId());
            responseParam.setList(list);
        } catch (Exception e) {
            throw new CommonException("获取收货地址列表失败：" + e.getMessage());
        }
        
        return responseParam;
    }

    @Override
    public void addAddress(UserAddress requestParam) {
        try {
            BizAssertUtil.notEmpty(requestParam.getName(), 10001, "收货人姓名不能为空");
            BizAssertUtil.notEmpty(requestParam.getPhone(), 10002, "收货人电话不能为空");
            BizAssertUtil.notEmpty(requestParam.getDetail(), 10003, "详细地址不能为空");

            requestParam.setUserId(SaTokenUtil.getLoginId().intValue());
            requestParam.setCreateTime(System.currentTimeMillis());
            requestParam.setUpdateTime(System.currentTimeMillis());
            String[] split = requestParam.getRegion().split(",");
            try {
                Map<String, Object> dictPCR = baseMapper.dictPCR(split[0], split[1], split[2]);
                // 检查Map是否为空
                if (dictPCR == null || dictPCR.isEmpty()) {
                    throw new CommonException("未找到对应的省市区信息");
                }
                // 安全地获取和转换值
                Object provinceIdObj = dictPCR.get("provinceId");
                Object cityIdObj = dictPCR.get("cityId");
                Object regionIdObj = dictPCR.get("regionId");
                
                if (provinceIdObj == null || cityIdObj == null || regionIdObj == null) {
                    throw new CommonException("省市区ID获取失败");
                }
                
                // 转换为Integer
                Integer provinceId = Integer.valueOf(provinceIdObj.toString());
                Integer cityId = Integer.valueOf(cityIdObj.toString());
                Integer regionId = Integer.valueOf(regionIdObj.toString());
                
                requestParam.setProvinceId(provinceId);
                requestParam.setCityId(cityId);
                requestParam.setRegionId(regionId);

            } catch (NumberFormatException e) {
                throw new CommonException("省市区ID转换失败：" + e.getMessage());
            } catch (Exception e) {
                throw new CommonException("获取省市区信息失败：" + e.getMessage());
            }
            this.save(requestParam);
            
        } catch (Exception e) {
            throw new CommonException("添加收货地址失败：" + e.getMessage());
        }
    }

    @Override
    public AddressWithRegion getAddressDetail(Long addressId) {
        AddressWithRegion responseParam = new AddressWithRegion();
        AddressInfo addressDetail = this.baseMapper.getAddressDetailById(addressId);
        BeanUtils.copyProperties(addressDetail, responseParam);
        
        // 检查region是否为空
        if (addressDetail.getRegion() != null) {
            String[] regions = {addressDetail.getRegion().getProvince(), addressDetail.getRegion().getCity(), addressDetail.getRegion().getRegion()};
            responseParam.setRegions(regions);
        } else {
            // 如果region为空，设置默认值
            String[] regions = {"", "", ""};
            responseParam.setRegions(regions);
        }
        
        return responseParam;
    }

    @Override
    public void editAddress(UserAddress requestParam) {
        try {
            BizAssertUtil.notEmpty(requestParam.getName(), 10001, "收货人姓名不能为空");
            BizAssertUtil.notEmpty(requestParam.getPhone(), 10002, "收货人电话不能为空");
            BizAssertUtil.notEmpty(requestParam.getDetail(), 10003, "详细地址不能为空");
            BizAssertUtil.notNull(requestParam.getAddressId(), 10004, "地址ID不能为空");
            requestParam.setUpdateTime(System.currentTimeMillis()/1000);
           
            String[] split = requestParam.getRegion().split(",");
            try {
                Map<String, Object> dictPCR = baseMapper.dictPCR(split[0], split[1], split[2]);
                // 检查Map是否为空
                if (dictPCR == null || dictPCR.isEmpty()) {
                    throw new CommonException("未找到对应的省市区信息");
                }
                // 安全地获取和转换值
                Object provinceIdObj = dictPCR.get("provinceId");
                Object cityIdObj = dictPCR.get("cityId");
                Object regionIdObj = dictPCR.get("regionId");
                
                if (provinceIdObj == null || cityIdObj == null || regionIdObj == null) {
                    throw new CommonException("省市区ID获取失败");
                }
                
                // 转换为Integer
                Integer provinceId = Integer.valueOf(provinceIdObj.toString());
                Integer cityId = Integer.valueOf(cityIdObj.toString());
                Integer regionId = Integer.valueOf(regionIdObj.toString());
                
                requestParam.setProvinceId(provinceId);
                requestParam.setCityId(cityId);
                requestParam.setRegionId(regionId);

            } catch (NumberFormatException e) {
                throw new CommonException("省市区ID转换失败：" + e.getMessage());
            } catch (Exception e) {
                throw new CommonException("获取省市区信息失败：" + e.getMessage());
            }
            this.updateById(requestParam);
            
        } catch (Exception e) {
            throw new CommonException("编辑收货地址失败：" + e.getMessage());
        }
    }

    @Override
    public void setDefaultAddress(Long addressId) {
        try {
            if (addressId == null) {
                throw new CommonException("地址ID不能为空");
            }
            UserAddress userAddress = this.baseMapper.selectById(addressId);
            if (userAddress == null) {
                throw new CommonException("地址不存在");
            }
            Long id = SaTokenUtil.getLoginId();
            if(userAddress.getUserId() != id.intValue()){
                throw new CommonException("您没有权限操作此地址");
            }
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(User::getAddressId, addressId);
            updateWrapper.eq(User::getUserId, id);
            userService.update(updateWrapper);
            
        } catch (Exception e) {
            throw new CommonException("设置默认收货地址失败：" + e.getMessage());
        }
    }
    @Override
    public void deleteAddress(Long addressId) {
        try {
            if (addressId == null) {
                throw new CommonException("地址ID不能为空");
            }
            UserAddress userAddress = this.baseMapper.selectById(addressId);
            if (userAddress == null) {
                throw new CommonException("地址不存在");
            }
            userAddress.setAddressId(0);
            this.baseMapper.deleteById(addressId);
            
        } catch (Exception e) {
            throw new CommonException("删除收货地址失败：" + e.getMessage());
        }
    }

    @Override
    public AddressResponseParam getRegionList(Long parentId) {
        AddressResponseParam responseParam = new AddressResponseParam();
        
        try {
            // TODO: 获取省市区列表
            // 这里需要注入RegionMapper并查询数据库
            

            
        } catch (Exception e) {
            throw new CommonException("获取省市区列表失败：" + e.getMessage());
        }
        
        return responseParam;
    }

    @Override
    public AddressResponseParam checkAddress(String token) {
        AddressResponseParam responseParam = new AddressResponseParam();
        
        try {
            if (token == null || token.isEmpty()) {
                throw new CommonException("用户令牌不能为空");
            }
            
            // TODO: 检查收货地址是否存在
            // 这里需要注入AddressMapper并查询数据库
            
            // 模拟检查结果
            responseParam.setHasAddress(true);
            
        } catch (Exception e) {
            throw new CommonException("检查收货地址失败：" + e.getMessage());
        }
        
        return responseParam;
    }
} 